import React, { Component } from 'react';
import styles from './style.scss';
import PropTypes from 'prop-types';

class CheckboxGroup extends Component {
    state = {
        checkedValue: []
    };

    static propTypes = {
        length: PropTypes.number,
        disabled: PropTypes.bool,
        defaultValue: PropTypes.array,
        value: PropTypes.any,
        name: PropTypes.string,
        onChange: PropTypes.func.isRequired
    };

    static defaultProps = {
        length: 1,
        disabled: false,
        defaultValue: [],
        value: []
    };

    onChange = e => {
        let { onChange, value } = this.props;
        const index = value.indexOf(e.target.value);
        if (value.length > 0) {
            if (index > -1) {
                value.splice(index, 1)
            } else {
                value.push(e.target.value)
            }
        } else {
            value.push(e.target.value)
        }
        this.setState({
            checkedValue: [].concat(value)
        });
        onChange(value);
    }

    renderChildren() {
        const { disabled, defaultValue, value, name, children } = this.props;
        if (defaultValue && !value) {
            return React.Children.map(children, child => {
                return React.cloneElement(child, {
                    disabled: child.props.disabled || disabled,
                    checked: defaultValue.indexOf(child.props.value) !== -1,
                    name,
                    onChange: this.onChange
                })
            });
        }

        return React.Children.map(children, child => {
            return React.cloneElement(child, {
                disabled: child.props.disabled || disabled,
                checked: value.indexOf(child.props.value) !== -1,
                name,
                onChange: this.onChange
            })
        });
    }

    render() {
        const style = this.props.style;
        return <div className={(this.props.length > 3 ? `${styles.checkboxGroup} ${styles.fixedWidth}` : `${styles.checkboxGroup}`)} style={style}>{this.renderChildren()}</div>;
    }
}

export default CheckboxGroup;